package cn.tellfish.studydemo.demo;

import org.junit.Before;
import org.junit.Test;

import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

public class AtomicTest {


//    private int THREADS = 100;

    private int count = 0;

//    @Before
//    public void init() {
//        System.out.println("before");
//    }

    @Test
    public void test1() throws InterruptedException {

//        System.out.println("test");

        AtomicTest atomicTest = new AtomicTest();
        Random random = new Random();

        int THREADS = 1000;

        CountDownLatch latch = new CountDownLatch(THREADS);
        for (int i = 0; i < THREADS; i++) {
            new Thread(() -> {
                try {
                    latch.countDown();
                    latch.await();
                    Thread.sleep(random.nextInt(10));
                    System.out.println("运行" + atomicTest.count++);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }

            }, "线程" + (i + 1)).start();
        }
        Thread.sleep(2000);

    }

    @Test
    public void test2() throws InterruptedException {

//        System.out.println("test");

//        AtomicTest atomicTest = new AtomicTest();
        AtomicInteger atomicInt = new AtomicInteger(0);
        Random random = new Random();

        int THREADS = 10000;

        CountDownLatch latch = new CountDownLatch(THREADS);
        for (int i = 0; i < THREADS; i++) {
            new Thread(() -> {
                try {
                    latch.countDown();
                    latch.await();
                    Thread.sleep(random.nextInt(10));
                    int andIncrement = atomicInt.getAndIncrement();
                    System.out.println("运行" + andIncrement);
                    if (andIncrement == (THREADS - 1)) {
                        System.out.println("-------------------------------------->");
                    }
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }

            }, "线程" + (i + 1)).start();
        }
        Thread.sleep(3000);

    }

}
